package com.itrip.itripbiz.controller;

import com.alibaba.fastjson.JSONArray;
import com.itrip.common.*;
import com.itrip.dto.Dto;
import com.itrip.entity.*;
import com.itrip.service.*;
import com.itrip.vo.order.*;
import com.itrip.vo.userinfo.ItripModifyUserLinkUserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;


@RestController
@RequestMapping("/biz/api")
public class HotelorderControler {
    @Resource
    private ItripHotelTempStoreService  itripHotelTempStoreService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private ItripHotelRoomService itripHotelRoomService;
    @Resource
    private ItripOrderLinkUserService itripOrderLinkUserService;
    @Resource
    private ItripHotelOrderService itripHotelOrderService;
    @Resource
    private ItripUserLinkUserService itripUserLinkUserService;
    //预生成订单信息
    @PostMapping("/hotelorder/getpreorderinfo")
    public Dto<RoomStoreVO> PostpreAdddorderVo(@RequestBody PreAddOrderVO preAddOrderVO, HttpServletRequest request) throws Exception {
        String tokenString = request.getHeader("token");
        ItripUser itripUser = (ItripUser) redisTemplate.opsForValue().get(tokenString);
        ItripHotel hotel = null;
        ItripHotelRoom itripHotelRoom = null;
        if(EmptyUtils.isEmpty(itripUser)){
              return DtoUtil.returnFail("token失效，请重新登录","100000");
        }
        if (EmptyUtils.isEmpty(preAddOrderVO.getHotelId())) {
            return DtoUtil.returnFail("hotelId不能为空", "100510");
        } else if (EmptyUtils.isEmpty(preAddOrderVO.getRoomId())) {
            return DtoUtil.returnFail("roomId不能为空", "100511");
        } else {
            ItripHotelRoom itripHotelRoom1 =itripHotelRoomService.getById(preAddOrderVO.getRoomId());

            RoomStoreVO roomStoreVO =itripHotelTempStoreService.queryRoomStore(preAddOrderVO);
            roomStoreVO.setCheckInDate(preAddOrderVO.getCheckInDate());
            roomStoreVO.setCheckOutDate(preAddOrderVO.getCheckOutDate());
            roomStoreVO.setPrice(BigDecimal.valueOf(itripHotelRoom1.getRoomPrice()));
            roomStoreVO.setCount(1);
            if(EmptyUtils.isNotEmpty(roomStoreVO)){
                roomStoreVO.setStore(roomStoreVO.getStore());
            }else{
                return DtoUtil.returnFail("暂时无房","100512");
            }
            return DtoUtil.returnSuccess("获取成功",roomStoreVO);
        }
    }
    @PostMapping("/hotelorder/addhotelorder")
    public Dto<Object> addHotelOrder(@RequestBody ItripAddHotelOrderVO itripAddHotelOrderVO, HttpServletRequest request) throws ParseException {

         SystemConfig systemConfig = new SystemConfig();
        Dto<Object> dto = new Dto<Object>();
        String tokenString = request.getHeader("token");
        ItripUser itripUser = (ItripUser) redisTemplate.opsForValue().get(tokenString);
        List<ItripUserLinkUser> linkUserslist = itripAddHotelOrderVO.getLinkUser();
        HashMap<String, Object> validateStoreMap = new HashMap<String, Object>();
        validateStoreMap.put("startTime", itripAddHotelOrderVO.getCheckInDate());
        validateStoreMap.put("endTime", itripAddHotelOrderVO.getCheckOutDate());
        validateStoreMap.put("hotelId", itripAddHotelOrderVO.getHotelId());
        validateStoreMap.put("roomId",itripAddHotelOrderVO.getRoomId().intValue());
        validateStoreMap.put("count", itripAddHotelOrderVO.getCount());
        List<ItripUserLinkUser> linkUserList = itripAddHotelOrderVO.getLinkUser();
        if(EmptyUtils.isEmpty(itripUser)){
            return DtoUtil.returnFail("token失效，请重新登录","100000");
        }
        //判断库存是否不足
        boolean flag = itripHotelTempStoreService.validateRoomStore(validateStoreMap);
        if(flag && null!=itripAddHotelOrderVO){
            Integer days = DateUtil.getBetweenDates(itripAddHotelOrderVO.getCheckInDate(),itripAddHotelOrderVO.getCheckOutDate()).size()-1;
            if(days <= 0){
                return DtoUtil.returnFail("退房日期必须大于入住日期", "100505");
            }
            ItripHotelOrder itripHotelOrder = new ItripHotelOrder();
            itripHotelOrder.setId(itripAddHotelOrderVO.getId());
            itripHotelOrder.setUserId(itripUser.getId());
            itripHotelOrder.setOrderType(itripAddHotelOrderVO.getOrderType());
            itripHotelOrder.setHotelId(itripAddHotelOrderVO.getHotelId());
            itripHotelOrder.setHotelName(itripAddHotelOrderVO.getHotelName());
            itripHotelOrder.setRoomId(itripAddHotelOrderVO.getRoomId());
            itripHotelOrder.setCount(itripAddHotelOrderVO.getCount().longValue());
            itripHotelOrder.setCheckInDate(itripAddHotelOrderVO.getCheckInDate());
            itripHotelOrder.setCheckOutDate(itripAddHotelOrderVO.getCheckOutDate());
            itripHotelOrder.setNoticePhone(itripAddHotelOrderVO.getNoticePhone());
            itripHotelOrder.setNoticeEmail(itripAddHotelOrderVO.getNoticeEmail());
            itripHotelOrder.setSpecialRequirement(itripAddHotelOrderVO.getSpecialRequirement());
            itripHotelOrder.setIsNeedInvoice(itripAddHotelOrderVO.getIsNeedInvoice());
            itripHotelOrder.setInvoiceHead(itripAddHotelOrderVO.getInvoiceHead());
            itripHotelOrder.setInvoiceType(itripAddHotelOrderVO.getInvoiceType().longValue());
            itripHotelOrder.setCreatedBy(itripUser.getId());
            StringBuilder linkUserName =new StringBuilder();
            int size = linkUserList.size();
            for (int i = 0; i < size; i++) {
                if(i !=size-1){
                      linkUserName.append(linkUserList.get(i).getLinkUserName()+",");
                }else{
                      linkUserName.append(linkUserList.get(i).getLinkUserName());
                }
            }
            itripHotelOrder.setLinkUserName(linkUserName.toString());
            itripHotelOrder.setBookingDays(days.longValue());
            if(tokenString.startsWith("token:PC")){
                itripHotelOrder.setBookType(0);
            }else if(tokenString.startsWith("token:MOBILE")){
                itripHotelOrder.setBookType(1);
            }else{
                itripHotelOrder.setBookType(2);
            }
            //支付之前生成的订单状态 为未支付
            itripHotelOrder.setOrderStatus(0);
            //生成订单号：机器码 +日期+（MD5）（商品IDs+毫秒数+1000000的随机数）
            StringBuilder md5String = new StringBuilder();
            md5String.append(itripHotelOrder.getHotelId());
            md5String.append(itripHotelOrder.getRoomId());
            md5String.append(System.currentTimeMillis());
            md5String.append(Math.random() * 1000000);
            String md5 = MD5.getMd5(md5String.toString(), 6);
            //生成订单编号
            StringBuilder orderNo = new StringBuilder();
            orderNo.append(systemConfig.getMachineCode());
            orderNo.append(DateUtil.format(new Date(), "yyyyMMddHHmmss"));
            orderNo.append(md5);
            itripHotelOrder.setOrderNo(orderNo.toString());
            //计算订单的总金额
            try {
                itripHotelOrder.setPayAmount(itripHotelOrderService.getOrderPayAmount(days * itripAddHotelOrderVO.getCount(), itripAddHotelOrderVO.getRoomId()));
                Map<String, String> map = itripHotelOrderService.itriptxAddItripHotelOrder(itripHotelOrder, linkUserList);
                DtoUtil.returnSuccess();
                dto = DtoUtil.returnSuccess("生成订单成功", map);
            } catch (Exception e) {
                e.printStackTrace();
                dto = DtoUtil.returnFail("生成订单失败", "100505");
            }

        }else if(flag && null==itripAddHotelOrderVO){
            dto = DtoUtil.returnFail("不能提交空，请填写订单信息", "100506");
        }else{
            dto = DtoUtil.returnFail("库存不足", "100507");
        }
        return dto;
    }
        //获取个人订单信息
        @GetMapping("/hotelorder/getpersonalorderinfo/{orderId}")
        public Dto getPersonalOrderInfo(@PathVariable("orderId") Long orderId,HttpServletRequest request) {
            Dto<Object> dto = null;
            String tokenString = request.getHeader("token");
            ItripUser itripUser = (ItripUser) redisTemplate.opsForValue().get(tokenString);
            if (null != itripUser) {
                if (null == orderId || "".equals(orderId)) {
                    return DtoUtil.returnFail("请传递参数：orderId", "100525");
                }

            try {
                ItripHotelOrder itripHotelOrder = itripHotelOrderService.getById(orderId);
                if (itripHotelOrder != null) {
                    ItripPersonalHotelOrderVO itripPersonalHotelOrderVO = new ItripPersonalHotelOrderVO();
                    itripPersonalHotelOrderVO.setId(itripHotelOrder.getId());
                    itripPersonalHotelOrderVO.setBookType(itripHotelOrder.getBookType());
                    itripPersonalHotelOrderVO.setCreationDate(itripHotelOrder.getCreationDate());
                    itripPersonalHotelOrderVO.setOrderNo(itripHotelOrder.getOrderNo());
                    //查询预订房间的信息
                    ItripHotelRoom room = itripHotelRoomService.getById(itripHotelOrder.getRoomId());
                    if (EmptyUtils.isNotEmpty(room)) {
                        itripPersonalHotelOrderVO.setRoomPayType(room.getPayType().intValue());
                    }
                    Integer orderStatus = itripHotelOrder.getOrderStatus().intValue();
                    itripPersonalHotelOrderVO.setOrderStatus(orderStatus);
                    SystemConfig systemConfig = new SystemConfig();
                    if (orderStatus == 1) {
                        itripPersonalHotelOrderVO.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessCancel()));
                        itripPersonalHotelOrderVO.setProcessNode("3");
                    } else if (orderStatus == 0) {
                        itripPersonalHotelOrderVO.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessOK()));
                        itripPersonalHotelOrderVO.setProcessNode("2");//订单支付
                    } else if (orderStatus == 2) {
                        itripPersonalHotelOrderVO.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessOK()));
                        itripPersonalHotelOrderVO.setProcessNode("3");//支付成功（未出行）
                    } else if (orderStatus == 3) {
                        itripPersonalHotelOrderVO.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessOK()));
                        itripPersonalHotelOrderVO.setProcessNode("5");//订单点评
                    } else if (orderStatus == 4) {
                        itripPersonalHotelOrderVO.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessOK()));
                        itripPersonalHotelOrderVO.setProcessNode("6");//订单完成
                    } else {
                        itripPersonalHotelOrderVO.setOrderProcess(null);
                        itripPersonalHotelOrderVO.setProcessNode(null);
                    }
                    itripPersonalHotelOrderVO.setPayAmount(itripHotelOrder.getPayAmount());
                    itripPersonalHotelOrderVO.setPayType(itripHotelOrder.getPayType());
                    itripPersonalHotelOrderVO.setNoticePhone(itripHotelOrder.getNoticePhone());
                    dto = DtoUtil.returnSuccess("获取个人订单信息成功", itripPersonalHotelOrderVO);
                }
            } catch (Exception e) {
                e.printStackTrace();
                dto = DtoUtil.returnFail("没有相关订单信息", "100526");
            }
            }else {
                dto = DtoUtil.returnFail("token失效，请重登录", "100000");
            }
            return dto;
        }
        //查询个人订单房型信息
        @GetMapping("/hotelorder/getpersonalorderroominfo/{orderId}")
        public Dto getPersonalOrderRoomInfo(@PathVariable("orderId") Long orderId, HttpServletRequest request){
            Dto<Object> dto = null;
            String tokenString = request.getHeader("token");
            ItripUser itripUser = (ItripUser) redisTemplate.opsForValue().get(tokenString);
            if(itripUser != null){
                if (null == orderId || "".equals(orderId)) {
                    return DtoUtil.returnFail("请传递参数：orderId", "100529");
                }
                try {
                    ItripPersonalOrderRoomVO vo = itripHotelOrderService.getItripHotelOrderRoomInfoById(orderId);
                    if (null != vo) {
                        dto = DtoUtil.returnSuccess("获取个人订单房型信息成功", vo);
                    } else {
                        dto = DtoUtil.returnFail("没有相关订单房型信息", "100530");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    dto = DtoUtil.returnFail("获取个人订单房型信息错误", "100531");
                }
            }else{
                dto = DtoUtil.returnFail("token失效，请重登录", "100000");
            }
           return dto;
        }
        //获取订单信息
       @GetMapping("/hotelorder/queryOrderById/{orderId}")
       public Dto queryOrderById(@PathVariable("orderId") Long orderId,HttpServletRequest request){
           ItripModifyHotelOrderVO itripModifyHotelOrderVO = null;
           String tokenString = request.getHeader("token");
           try {
               ItripUser itripUser = (ItripUser) redisTemplate.opsForValue().get(tokenString);
               if(EmptyUtils.isEmpty(itripUser)){
                   return DtoUtil.returnFail("token失效，请重登录", "100000");
               }
               ItripHotelOrder order = itripHotelOrderService.getById(orderId);
               if(EmptyUtils.isEmpty(order)){
                   return DtoUtil.returnFail("没有查询到相应订单", "100533");
               }
               itripModifyHotelOrderVO = new ItripModifyHotelOrderVO();
               BeanUtils.copyProperties(order, itripModifyHotelOrderVO);
               Map<String, Object> param = new HashMap<String, Object>();
               param.put("orderId", order.getId());
               List<ItripOrderLinkUserVo> itripOrderLinkUserList = itripOrderLinkUserService.getItripOrderLinkUserListByMap(param);
               itripModifyHotelOrderVO.setItripOrderLinkUserList(itripOrderLinkUserList);
               return DtoUtil.returnSuccess("获取订单成功", itripModifyHotelOrderVO);
           } catch (Exception e) {
               e.printStackTrace();
               return DtoUtil.returnFail("系统异常", "100534");
           }
       }
       //查询个人酒店订单列表
       @PostMapping("/hotelorder/getpersonalorderlist")
       public Dto getPersonalOrderList(@RequestBody ItripSearchOrderVO itripSearchOrderVO,HttpServletRequest request){
           String tokenString = request.getHeader("token");
               ItripUser itripUser = (ItripUser) redisTemplate.opsForValue().get(tokenString);
               Page page = new Page();
               if(null != itripUser){
                    if(itripSearchOrderVO.getOrderType() == null){
                          return DtoUtil.returnFail("请传递参数：orderType","100501");
                    }
                   if (itripSearchOrderVO.getOrderStatus() == null) {
                       return DtoUtil.returnFail("请传递参数：orderStatus", "100502");
                   }
                   Map<String, Object> param = new HashMap<>();
                   param.put("orderType", itripSearchOrderVO.getOrderType() == -1 ? null : itripSearchOrderVO.getOrderType());
                   param.put("orderStatus", itripSearchOrderVO.getOrderStatus()  == -1 ? null : itripSearchOrderVO.getOrderStatus());
                   param.put("userId", itripUser.getId());
                   param.put("orderNo", itripSearchOrderVO.getOrderNo());
                   param.put("linkUserName", itripSearchOrderVO.getLinkUserName());
                   param.put("startDate", itripSearchOrderVO.getStartDate());
                   param.put("endDate", itripSearchOrderVO.getEndDate());
                   try {
                       page = itripHotelOrderService.queryOrderPageByMap(param,itripSearchOrderVO.getPageNo(),itripSearchOrderVO.getPageSize());

                   } catch (Exception e) {
                       e.printStackTrace();
                       DtoUtil.returnFail("获取个人订单列表错误", "100503");
                   }
               }else{
                   DtoUtil.returnFail("token失效，请重登录", "100000");
               }
           return  DtoUtil.returnSuccess("获取个人订单列表成功", page);
       }
       //修改联系人
       @PostMapping("/userinfo/modifyuserlinkuser")
       public Dto updateUserLinkUser(@RequestBody ItripModifyUserLinkUserVO itripModifyUserLinkUserVO, HttpServletRequest request){
           String tokenString  = request.getHeader("token");
           ItripUser itripUser = (ItripUser) redisTemplate.opsForValue().get(tokenString);
           if(null != itripUser && null != itripModifyUserLinkUserVO){
               ItripUserLinkUser itripUserLinkUser = new ItripUserLinkUser();
               itripUserLinkUser.setId(itripModifyUserLinkUserVO.getId());
               itripUserLinkUser.setLinkUserName(itripModifyUserLinkUserVO.getLinkUserName());
               itripUserLinkUser.setLinkIdCardType(itripModifyUserLinkUserVO.getLinkIdCardType().longValue());
               itripUserLinkUser.setLinkIdCard(itripModifyUserLinkUserVO.getLinkIdCard());
               itripUserLinkUser.setUserId(itripUser.getId());
               itripUserLinkUser.setLinkPhone(itripModifyUserLinkUserVO.getLinkPhone());
               itripUserLinkUser.setModifiedBy(itripUser.getId());
               itripUserLinkUser.setModifyDate(new Date(System.currentTimeMillis()));
               try {
                   itripUserLinkUserService.modifyItripUserLinkUser(itripUserLinkUser);
               } catch (Exception e) {
                   e.printStackTrace();
                   return DtoUtil.returnFail("修改常用联系人失败", "100421");
               }
               return DtoUtil.returnSuccess("修改常用联系人成功");
           }else if(null != itripUser && null == itripModifyUserLinkUserVO){
               return DtoUtil.returnFail("不能提交空，请填写常用联系人信息","100422");
           }else{
               return DtoUtil.returnFail("token失效，请重新登录", "100000");
           }
       }
       //删除联系人
    @GetMapping("/userinfo/deluserlinkuser")
    public Dto delUserLinkUser(Long[] ids, HttpServletRequest request){
        String tokenString  = request.getHeader("token");
        ItripUser itripUser = (ItripUser) redisTemplate.opsForValue().get(tokenString);
        List<Long> idsList = new ArrayList<Long>();
        if(null != itripUser && EmptyUtils.isNotEmpty(ids)){
            try {
                List<Long> linkUserIds = itripOrderLinkUserService.getItripOrderLinkUserIdsByOrder();
                Collections.addAll(idsList, ids);
                idsList.retainAll(linkUserIds);
                if(idsList.size() > 0){
                    return DtoUtil.returnFail("所选的常用联系人中有与某条待支付的订单关联的项，无法删除","100431");
                }else{
                    itripUserLinkUserService.deleteItripUserLinkUserByIds(ids);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail("删除常用联系人失败","100432");
            }
            return DtoUtil.returnSuccess("删除常用联系人成功");
        } else if(null != itripUser && EmptyUtils.isEmpty(ids)){
            return DtoUtil.returnFail("请选择要删除的常用联系人","100433");
        }else{
            return DtoUtil.returnFail("token失效，请重新登录","100000");
        }
    }
}
